package com.stone.mythread.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache cache = new MyCache();
        // 创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                cache.put(num + "", num + "");
            }, String.valueOf(i)).start();
        }

        // 创建线程取数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                cache.get(num + "");
            }, String.valueOf(i)).start();
        }

    }

}

// 资源类
class MyCache {
    // 创建 Map 集合
    private volatile Map<String, Object> map = new HashMap<>();

    // 创建读写锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        // 添加写锁
        readWriteLock.writeLock().lock();
        try {
            System.err.println(Thread.currentThread().getName() + " 正在写操作 " + key + " : " + value);
            TimeUnit.MICROSECONDS.sleep(300);

            map.put(key, value);
            System.err.println(Thread.currentThread().getName() + " 写完了 " + key + " : " + value);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放写锁
            readWriteLock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        Object result = null;
        // 添加读锁
        readWriteLock.readLock().lock();
        try {
            System.err.println(Thread.currentThread().getName() + " 正在读取操作" + key + " : " + result);
            TimeUnit.MICROSECONDS.sleep(100);

            result = map.get(key);
            System.err.println(Thread.currentThread().getName() + " 取完了" + key + " : " + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
        return result;
    }
}
